const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()

module.exports = async function(params){
  
  var skip = (params.pageNum - 1) * params.pageSize
  var limit = params.pageSize
  delete params.pageNum
  delete params.pageSize

  if(params.content){
    params.content = db.RegExp({
      regexp: params.content,
      options: 'im',
    })
  }
    
  var $ = db.command.aggregate
  let res = await db.collection('prizeWin').aggregate()
    .match(params)
    .skip(skip)
    .sort({
      createDate: -1
    })
    .limit(limit)
    
    .lookup({
      from: 'prize',
      localField: "prizeId",
      foreignField: "_id",
      as: "prizeList"
    })
    .replaceRoot({
      newRoot: $.mergeObjects([ $.arrayElemAt(['$prizeList', 0]), '$$ROOT' ])
    })
    .project({
      prizeList: 0
    })
    .end()
   
    return res
}